import {
  addDepartmentMember, getDepartmentMembers,
  getDepartments,
  updateDepartmentPacket,
  updateDepartments, updateMemberDepartment, updateMemberStatus
} from "@/services/department/department";
import React, {useEffect, useRef, useState} from "react";
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProFormSwitch,
  ProFormText,
  ProFormTreeSelect,
  ProTable
} from "@ant-design/pro-components";
import {Button, Col, Flex, message, Row, Tree, TreeDataNode, Spin, Switch} from "antd";
import {TableListItem} from "@/pages/list/table-list/data";
import moment from "moment";
import {blackCustomer} from "@/services/customer/customer";

const Department: React.FC = () => {
  const [loading, setLoading] = useState(false);

  const actionRef = useRef<ActionType>();
  const redPacketRef = useRef();
  const addDepartmentRef = useRef();
  const modifyMemberDepartmentRef = useRef();
  const modifyMemberInfoRef = useRef();
  const treeRef = useRef<any>();
  const [currentIndex, setCurrentIndex] = useState(0)
  const [size, setSize] = useState(10)

  const [modifyDepartmentInfoModal, setModifyDepartmentInfoModal] = useState<boolean>(false); //调整门店信息
  const [addMemberModal, setAddMemberModal] = useState<boolean>(false); //添加成员
  const [modifyMemberDepartmentModal, setModifyMemberDepartmentModal] = useState<boolean>(false); //修改成员所属门店
  const [modifyRedPacket, setModifyRedPacket] = useState<boolean>(false); //调整邀约红包奖励
  const [addDepartmentModal, setAddDepartmentModal] = useState<boolean>(false); //添加下级门店

  const [treeData, setTreeData] = useState([])
  const [treeExpandKeys, setTreeExpandKeys] = useState<any[]>([])
  const [currentDepartment, setCurrentDepartment] = useState<number>(0)
  const [record, setRecord] = useState(null)

  const [isEdit, setIsEdit] = useState(false)

  const initTreeData = async () => {
    const {data} = await getDepartments();
    console.log('departments', data)

    const expandKeys = []
    data.forEach(department => {
      expandKeys.push(department.wxDid)
    })
    console.log('expand keys', expandKeys)

    const buildTreeNodes = async (departments) => {
      const findChildren = (parent) => {
        return departments.filter(department => department.parentId === parent.wxDid)
          .map(department => {
            const item: TreeDataNode = {
              key: department.wxDid,
              value: department.wxDid,
              title: department.name,
              department: department,
              parentId: department.parentId,
              children: findChildren(department)
            }
            return item
          })
      };
      const rootNodes = departments.filter(department => department.parentId === 0)
        .map(department => {
          const item: TreeDataNode = {
            key: department.wxDid,
            value: department.wxDid,
            title: department.name,
            department: department,
            parentId: department.parentId,
            children: findChildren(department)
          }
          return item
        });
      return rootNodes;
    }
    const treeNodeData = await buildTreeNodes(data);
    console.log('treeData', treeNodeData)
    setTreeData(treeNodeData);
    setTreeExpandKeys(expandKeys)
  }

  useEffect(() => {
    initTreeData()
  }, []);

  const columns = [
    {
      title: '序号',
      dataIndex: 'wxUid',
      width: 80,
    }, {
      title: '姓名',
      dataIndex: 'name',
      width: 120,
    }, {
      title: '所属门店',
      dataIndex: 'departmentName',
      width: 120,
    }, {
      title: '职务',
      dataIndex: 'position',
      valueEnum: {
        0: {text: '销售员'},
        1: {text: '管理员'},
      }
    }, {
      title: '向顾客展示二维码',
      dataIndex: 'showQrCode',
    }, {
      title: '手机号',
      dataIndex: 'mobile',
    }, {
      title: '在职状态',
      dataIndex: 'active',
      render: (text, record) => {
        return <Switch checked={record.active} onChange={async (checked: boolean, event: Event) => {
          console.log('switch', record)
          setLoading(true)
          const params = {
            wxUid: record.wxUid,
            status: checked ? 1 : 0,
          }
          const res = await updateMemberStatus(params)
          setLoading(false)

          if (res.code === 1) {
            actionRef.current?.reload()
            message.success('操作成功')
          } else {
            message.error('操作失败')
          }
        }}/>
      }
    }, {
      title: '加入时间',
      dataIndex: 'joinTime',
      render: (text) => text === '-' ? text : moment(text).format('YYYY-MM-DD HH:mm:ss')
    }, {
      title: '离职时间',
      dataIndex: 'leaveTime',
      render: (text) => text === '-' ? text : moment(text).format('YYYY-MM-DD HH:mm:ss')
    }, {
      title: '操作',
      render: (text, record, _, action) => [
        <a onClick={() => {
          console.log('edit member', record)
          setRecord(record)
          setIsEdit(true)
          setAddMemberModal(true)
        }}>编辑</a>,
        <span>&nbsp;&nbsp;</span>,
        <a onClick={() => {
          console.log('modify member department', record)
          setRecord(record)
          setModifyMemberDepartmentModal(true)
        }}>
          调整门店
        </a>,
      ],
    },
  ]
  const tableListDataSource: TableListItem[] = [];
  for (let i = 0; i < 5; i += 1) {
    tableListDataSource.push({
      id: i,
      name: '测试',
      department: '门店1',
    });
  }
  return (
    <PageContainer title='门店管理'>
      <Spin spinning={loading} tip="加载中...">
        <Row>
          <Col span={6}>
            <div>
              <Tree
                defaultExpandAll={true}
                expandedKeys={treeExpandKeys}
                treeData={treeData}
                height={500}
                onSelect={(selectedKeys, info) => {
                  console.log('selected', info.selectedNodes[0])
                  setCurrentDepartment(info.selectedNodes[0] ? info.selectedNodes[0].department : null)
                  actionRef.current?.reload()
                }}
              />
            </div>
          </Col>
          <Col span={1}></Col>
          <Col span={17}>
            <ProTable
              actionRef={actionRef}
              rowKey="id"
              request={async () => {
                const params: Department.GetDepartmentMemberParams = {
                  wxDid: currentDepartment.wxDid,
                  page: currentIndex,
                  size: size
                }
                console.log('get department member param', params)
                const ret = await getDepartmentMembers(params)
                console.log('get department member', ret)
                return {
                  data: ret.data.records,
                  success: true,
                  total: ret.data.total
                }
              }}
              pagination={{
                pageSize: size,
                onChange: (page) => setCurrentIndex(page),
              }}
              columns={columns}
              search={false}
              dateFormatter="string"
              // headerTitle="表格标题"
              toolBarRender={() => [
                <Button key="btn_add" type="primary" onClick={() => {
                  if (!currentDepartment) {
                    message.error('请选择上级门店')
                    return
                  }
                  setAddDepartmentModal(true)
                }}>添加下级门店</Button>,
                <Button key="button" type="primary" onClick={() => {
                  if (!currentDepartment) {
                    message.error('请选择门店')
                    return
                  }
                  setModifyDepartmentInfoModal(true)
                }}>修改门店信息</Button>,
                <Button key="button" type="primary" onClick={() => {
                  console.log('current department', currentDepartment)
                  if (!currentDepartment) {
                    message.error('请选择门店')
                    return
                  }
                  setModifyRedPacket(true)
                }}>调整邀约红包奖励</Button>,
                <Button key="button" type="primary" onClick={() => {
                  if (!currentDepartment) {
                    message.error('请选择门店')
                    return
                  }
                  setIsEdit(false)
                  setAddMemberModal(true)
                }}>添加成员</Button>
              ]}
            />
          </Col>
        </Row>

        {/*修改成员所属门店*/}
        <ModalForm
          formRef={modifyMemberDepartmentRef}
          title="调整所属门店"
          open={modifyMemberDepartmentModal}
          layout={{
            labelCol: {span: 4},
            wrapperCol: {span: 14},
          }}
          onFinish={async (values) => {
            console.log(values)
            const params = {
              wxDid: values.department,
              wxUid: record.wxUid,
            }
            console.log('update member department param', params)
            const ret = await updateMemberDepartment(params)
            if (!ret) {
              message.error('修改成员所属门店失败')
              return false
            } else {
              message.success('修改成员所属门店成功')
              return true;
            }
          }}
          onOpenChange={(open) => {
            setModifyMemberDepartmentModal(open)
            modifyMemberDepartmentRef.current?.setFieldsValue({
              department: currentDepartment.wxDid
            })
          }}
        >
          <ProFormTreeSelect
            label={'所属门店'}
            name="department"
            placeholder="请选择所属门店"
            width={330}
            rules={[{required: true, message: '请选择所属门店'}]}
            request={async () => {
              return treeData
            }}
            // tree-select args
            fieldProps={{
              treeDefaultExpandAll: true,
              suffixIcon: null,
              filterTreeNode: true,
              popupMatchSelectWidth: false,
              autoClearSearchValue: true,
              multiple: false,
              treeNodeFilterProp: 'title',
              fieldNames: {
                label: 'title',
              },
            }}
          />
        </ModalForm>
        {/*调整邀约红包奖励*/}
        <ModalForm
          formRef={redPacketRef}
          title="调整邀约红包奖励"
          width={500}
          open={modifyRedPacket}
          layout={{
            labelCol: {span: 4},
            wrapperCol: {span: 14},
          }}
          onFinish={async (values) => {
            console.log(values)
            const params: Department.DepartmentUpdatePacketParams = {
              inviteRewardStart: values.inviteRewardStart,
              inviteRewardEnd: values.inviteRewardEnd,
              quizCount: values.quizCount,
              wxDid: currentDepartment.wxDid
            }
            console.log('update packet param', params)
            const ret = await updateDepartmentPacket(params)
            if (!ret) {
              message.error('调整邀约红包奖励失败')
              return false
            } else {
              message.success('调整邀约红包奖励成功')
              const dep = currentDepartment
              dep.inviteRewardStart = values.inviteRewardStart
              dep.inviteRewardEnd = values.inviteRewardEnd
              dep.quizCount = values.quizCount
              setCurrentDepartment(dep)
              return true;
            }
          }}
          onOpenChange={(open) => {
            setModifyRedPacket(open)
            redPacketRef.current?.setFieldsValue({
              inviteRewardStart: currentDepartment.inviteRewardStart,
              inviteRewardEnd: currentDepartment.inviteRewardEnd,
              quizCount: currentDepartment.quizCount,
            })
          }}
        >
          <Row>
            <Col span={8}>邀约奖励：</Col>
            <Col span={5}>
              <ProFormText
                width={80}
                name="inviteRewardStart"
                rules={[{required: true, message: '请输入邀约奖励'}]}
                // tooltip="最长为 24 位"
                placeholder="请输入邀约红包奖励"
              />
            </Col>
            <Col span={1}>-</Col>
            <Col span={8}>
              <ProFormText
                width={80}
                name="inviteRewardEnd"
                rules={[{required: true, message: '请输入邀约奖励'}]}
                // tooltip="最长为 24 位"
                placeholder="请输入邀约红包奖励"
              />
            </Col>
          </Row>
          <Row>
            <Col span={8}>被邀请人答题红包</Col>
            <Col span={5}>
              <ProFormText
                width={80}
                name="quizCount"
                rules={[
                  {required: true, message: '请输入邀约奖励'},
                  {pattern: /^[1-9]$/, message: '请输入1-9之间的数字'}
                ]}
                // tooltip="最长为 24 位"
                placeholder="请输入邀约红包奖励"
              />
            </Col>
            <Col span={8}>
              次，发放邀约奖励
            </Col>
          </Row>
          <Row>
            <Col span={10}>
              默认次数为1，最多可输入9
            </Col>
          </Row>
        </ModalForm>

        {/*修改门店信息*/}
        <ModalForm
          formRef={addDepartmentRef}
          title="修改门店信息"
          width={500}
          open={modifyDepartmentInfoModal}
          layout={{
            labelCol: {span: 4},
            wrapperCol: {span: 14},
          }}
          onFinish={async (values) => {
            console.log(values)
            const params: Department.DepartmentUpdateParams = {
              name: values.departmentName,
              parentId: values.parentDepartment,
              wxDid: currentDepartment.wxDid
            }
            console.log('update department param', params)
            const res = await updateDepartments(params)
            if (res.code !== 1) {
              message.error('修改门店信息失败')
              return false
            } else {
              message.success('修改门店信息成功')
              initTreeData()
              return true;
            }
          }}
          onOpenChange={(open) => {
            setModifyDepartmentInfoModal(open)
            if (open) {
              addDepartmentRef.current?.setFieldsValue({
                departmentName: currentDepartment ? currentDepartment.name : '',
                parentDepartment: currentDepartment ? currentDepartment.parentId : 0,
              })
            }
          }}
        >
          <ProFormTreeSelect
            label={'上级门店'}
            name="parentDepartment"
            placeholder="请选择上级门店"
            width={330}
            rules={[{required: true, message: '请选择上级门店'}]}
            request={async () => {
              const parentNodes = [
                {
                  key: 0,
                  value: 0,
                  title: '无',
                  department: '无',
                },
                ...treeData
              ]
              return parentNodes
            }}
            // tree-select args
            fieldProps={{
              // value: currentParentDepartment,
              // value: parentDepartmentTreeSelectedNode,
              // treeData: parentDepartmentTreeData,
              treeDefaultExpandAll: true,
              suffixIcon: null,
              filterTreeNode: true,
              popupMatchSelectWidth: false,
              autoClearSearchValue: true,
              multiple: false,
              treeNodeFilterProp: 'title',
              fieldNames: {
                label: 'title',
              },
            }}
          />
          <ProFormText
            width="md"
            name="departmentName"
            label="门店名称"
            rules={[{required: true, message: '请输入门店名称'}]}
            // tooltip="最长为 24 位"
            placeholder="请输入门店名称"
          />
        </ModalForm>

        {/*添加成员弹窗*/}
        <ModalForm
          formRef={modifyMemberInfoRef}
          title={isEdit ? '编辑成员' : "添加成员"}
          width={500}
          open={addMemberModal}
          layout={{
            labelCol: {span: 4},
            wrapperCol: {span: 14},
          }}
          onFinish={async (values) => {
            console.log(values)
            const params: Department.DepartmentMemberParams = {
              mobile: values.mobile,
              name: values.name,
              password: values.password,
              position: values.position ? 1 : 0,
              wxDid: currentDepartment.wxDid
            }
            if (isEdit) {
              params.wxUid = record.wxUid
            }
            console.log('add member param', params)
            const res = await addDepartmentMember(params)
            if (res.code !== 1) {
              message.error('操作失败,' + res.msg)
              return false
            } else {
              message.success('操作成功')
              actionRef.current?.reload()
              return true;
            }
          }}
          onOpenChange={(open) => {
            setAddMemberModal(open)
            if (!open) {
              modifyMemberInfoRef.current?.resetFields()
            }
            if (open && isEdit) {
              modifyMemberInfoRef.current?.setFieldsValue({
                name: record.name,
                mobile: record.mobile,
                position: record.position === "1",
              })
            }
          }}
        >
          <ProFormText
            width="md"
            name="name"
            label="员工姓名"
            rules={[{required: true, message: '请输入员工姓名'}]}
            readonly={isEdit}
            // tooltip="最长为 24 位"
            placeholder="请输入员工姓名"
          />
          <ProFormText
            width="md"
            name="mobile"
            label="手机号码"
            rules={[{required: true, message: '请输入手机号'}]}
            readonly={isEdit}
            placeholder="请输入手机号码"
          />
          <ProFormText.Password
            width="md"
            name="password"
            label="登录密码"
            rules={[{required: true, message: '请输入登录密码'}]}
            placeholder="请输入登录密码"
          />
          <ProFormSwitch name="position" label="门店管理员"/>
        </ModalForm>
        <ModalForm
          formRef={addDepartmentRef}
          title="添加下级门店"
          width={500}
          open={addDepartmentModal}
          onOpenChange={(open) => {
            setAddDepartmentModal(open)
            if (open) {
              addDepartmentRef.current?.setFieldsValue({
                name: '',
                parentName: currentDepartment.name,
                parentId: currentDepartment.wxDid,
              })
            }
          }}
          onFinish={async (values) => {
            console.log(values)
            const params: Department.DepartmentUpdateParams = {
              name: values.departmentName,
              parentId: values.parentId,
            }
            console.log('add department param', params)
            const res = await updateDepartments(params)
            if (res.code !== 1) {
              message.error('添加门店信息失败')
              return false
            } else {
              message.success('添加门店信息成功')
              initTreeData()
              return true;
            }
          }}
        >
          <ProFormText
            width="md"
            name="parentName"
            label="上级门店名称"
            disabled={true}
          />
          <ProFormText hidden={true} name="parentId"/>
          <ProFormText
            width="md"
            name="departmentName"
            label="门店名称"
            rules={[{required: true, message: '请输入门店名称'}]}
            // tooltip="最长为 24 位"
            placeholder="请输入门店名称"/>
        </ModalForm>
      </Spin>
    </PageContainer>
  );
}

export default Department;
